﻿using ECommerce.Web.Validation;
using FluentValidation;
using FluentValidation.Results;
using NHibernate.Event;

namespace ECommerce.Web.NHibernate.EventListeners
{
    public class ValidationEventListener : IPreInsertEventListener, IPreUpdateEventListener
    {
        private static readonly IValidatorFactory ValidatorFactory = new ServiceLocatorValidatorFactory();

        public bool OnPreInsert(PreInsertEvent preInsertEvent)
        {
            ValidateEntity(preInsertEvent.Entity);

            return false;
        }

        public bool OnPreUpdate(PreUpdateEvent preUpdateEvent)
        {
            ValidateEntity(preUpdateEvent.Entity);

            return false;
        }

        private void ValidateEntity(object entity)
        {
            var entityType = entity.GetType();
            var validatorType = typeof(IValidator<>).MakeGenericType(entityType);

            IValidator validator = ValidatorFactory.GetValidator(validatorType);

            if (validator == null)
            {
                return;
            }

            ValidationResult result = validator.Validate(entity);

            if (!result.IsValid)
            {
                throw new ValidationException(result);
            }

        }
    }
}
